package csel.view;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

public class ViewUtils
{
	/**
	 * FileFilter class to restrict FileDialogs to .sav files.
	 * @author david
	 */
	private static class SaveGameFileFilter extends FileFilter
	{

		@Override
		public boolean accept(File file)
		{
			return "sav".equals(getExtension(file));
		}

		@Override
		public String getDescription()
		{
			return "Save Game Files (*.sav)";
		}
		
	}

    /**
     * Get the extension of a file.
     * 
     * Copied from Sun.
     */ 
    private static String getExtension(File f)
    {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
        }
        return ext;
    }
    
	/**
	 * Utility method to make a JFileChooser just how we want it.
	 */
	private static final JFileChooser makeFileChooser()
	{
		JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));
		
		fc.setFileFilter(new SaveGameFileFilter());
		
		return fc;
	}
	
	/**
	 * Prompts the user with an OpenFile dialog.
	 * @return the filepath that the user chose, or <strong>null</strong> if canceled.
	 */
	public static String promptOpenDialog(Viewport parent)
	{
		JFileChooser fc;
		
		fc = makeFileChooser();
		
		if (fc.showOpenDialog(parent.getContainer()) != JFileChooser.APPROVE_OPTION)
		{
			System.out.printf("[VIEW] User canceled open dialog.\n");
			return null;
		}
		
		return fc.getSelectedFile().getAbsolutePath();
	}

	/**
	 * Prompts the user with an SaveFile dialog. Will automatically append the extension
	 * if the user does not pick one.
	 * @return the filepath that the user chose, or <strong>null</strong> if canceled.
	 */
	public static String promptSaveDialog(Viewport parent)
	{
		JFileChooser fc;
		File file;
		
		fc = makeFileChooser();
		
		if (fc.showSaveDialog(parent.getContainer()) != JFileChooser.APPROVE_OPTION)
		{
			System.out.printf("[VIEW] User canceled save dialog.\n");
			return null;
		}
		
		file = fc.getSelectedFile();
		return (getExtension(file) == null) ?
				file.getAbsolutePath() + ".sav" : file.getAbsolutePath();
	}
}
